package com.lesg.search;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jayway.jsonpath.JsonPath;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class ElasticExecutor {

    private static Logger logger =   LoggerFactory.getLogger(ElasticExecutor.class);
    private static OkHttpClient client =
            new OkHttpClient.Builder()
                    .connectTimeout(120, TimeUnit.SECONDS)//设置连接超时时间
                    .readTimeout(180, TimeUnit.SECONDS)//设置读取超时时间
                    .build();



    public static List<String> getDocumentTypes(String content) {
        return JsonPath.read(content, "$.._type");
    }

    public static List<String> getDocumentIds(String content) {
        return JsonPath.read(content, "$.._id");

    }



    /**
     * 根据documentId获取--source的内容,供后续json串的比较
     *
     * @param index
     * @param documentId
     * @return
     * @throws IOException
     */
    public static String getDocContentById(final String index,
                                           final String type,
                                           final String documentId) {
        final Request request = new Request.Builder().url(index + "/" + type + "/" + documentId).get().build();
        try (Response response = client.newCall(request).execute()) {
            if (response.code() != 200) {
                logger.error("Search document " + documentId + " failed. Response status is:" + response.code());
                return null;
            }
            String content = response.body().string();
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();

            final Map map = gson.fromJson(content, Map.class);

            final Object source = map.get("_source");

            return source != null ? gson.toJson(source) : null;

        }catch(IOException ioe){
            logger.error("Failed to connecton index {} exception: {} ", index, ioe.getMessage());
            return null;
        }
    }




    public static String getCategoryPath(String RootDir, String prefix, String category){
        StringBuilder fullpath = new StringBuilder();
        fullpath.append(RootDir );
        fullpath.append(prefix);
        fullpath.append(category);
        fullpath.append(".json");
        return fullpath.toString();
    }

    public static String retriveQueryResponseContent(final String index,String queryStr) throws IOException {
        String bodyType = "application/json; charset=utf-8";
        final Request request = new Request.Builder().url(index + "/_search")
                .post(RequestBody.create(MediaType.parse(bodyType), queryStr))
                .build();
        try (Response response = client.newCall(request).execute()) {

            return response.code() == 200 ? response.body().string() : null;
        }
    }
}
